# backend/api/v1/user_subscriptions.py - 完整修复版本
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from backend.database import get_db
from backend.schemas import user_subscription as us_schemas
from backend.schemas.user_subscription import UserSubscriptionSwitchNode, UserSubscriptionSwitchResponse
from backend.crud import user_subscription as crud
from backend.crud.user_subscription import switch_user_subscription_node, can_switch_node, get_user_subscriptions_by_id
from backend.api.deps import get_current_user

router = APIRouter(prefix="/user-subscriptions", tags=["user-subscriptions"])


@router.post("/", response_model=us_schemas.UserSubscriptionOut)
async def create_us(
        data: us_schemas.UserSubscriptionCreate,
        db: AsyncSession = Depends(get_db),
        current_user=Depends(get_current_user)
):
    us = await crud.create_user_subscription(db, data)
    if not us:
        raise HTTPException(status_code=400, detail="Invalid data")
    return us


# 无斜杠版本
@router.get("/user/{user_id}", response_model=list[us_schemas.UserSubscriptionOut])
async def list_us_by_user_no_slash(
        user_id: str,
        db: AsyncSession = Depends(get_db),
        current_user=Depends(get_current_user)
):
    return await crud.get_user_subscriptions(db, user_id)


# 有斜杠版本
@router.get("/user/{user_id}/", response_model=list[us_schemas.UserSubscriptionOut])
async def list_us_by_user(
        user_id: str,
        db: AsyncSession = Depends(get_db),
        current_user=Depends(get_current_user)
):
    return await crud.get_user_subscriptions(db, user_id)


@router.put("/{user_subscription_id}/switch-node", response_model=UserSubscriptionSwitchResponse)
async def switch_subscription_node(
        user_subscription_id: str,
        switch_data: UserSubscriptionSwitchNode,
        db: AsyncSession = Depends(get_db),
        current_user=Depends(get_current_user)
):
    """
    切换用户订阅的节点 - 兼容 new_node_id 和 node_id 两种参数
    """
    # 详细的调试信息
    print(f"🔍 节点切换请求调试信息:")
    print(f"   用户订阅ID: {user_subscription_id}")
    print(f"   原始请求数据: {switch_data.dict()}")
    print(f"   new_node_id: {switch_data.new_node_id}")
    print(f"   node_id: {switch_data.node_id}")
    print(f"   最终使用的节点ID: {switch_data.get_final_node_id()}")

    try:
        # 使用验证后的最终节点ID
        new_node_id = switch_data.get_final_node_id()

        if not new_node_id:
            raise HTTPException(
                status_code=422,
                detail="必须提供 new_node_id 或 node_id 参数"
            )

        # 验证用户订阅ID格式
        try:
            import uuid
            uuid.UUID(user_subscription_id)
        except ValueError:
            raise HTTPException(
                status_code=400,
                detail="用户订阅ID格式无效"
            )

        # 验证新节点ID格式
        try:
            uuid.UUID(new_node_id)
        except ValueError:
            raise HTTPException(
                status_code=422,
                detail=f"节点ID格式无效: {new_node_id}"
            )

        # 1. 验证用户订阅是否存在且属于当前用户
        user_subs = await get_user_subscriptions_by_id(db, user_subscription_id)
        if not user_subs:
            raise HTTPException(status_code=404, detail="用户订阅不存在")

        user_sub = user_subs[0]
        print(f"✅ 找到用户订阅: {user_sub.id}, 用户ID: {user_sub.user_id}")

        # 2. 检查权限（用户只能操作自己的订阅）
        if str(user_sub.user_id) != str(current_user.id):
            print(f"❌ 权限验证失败: 当前用户 {current_user.id} 无权操作订阅 {user_sub.id}")
            raise HTTPException(status_code=403, detail="无权操作此订阅")

        print("✅ 权限验证通过")

        # 3. 检查是否可以切换节点
        can_switch = await can_switch_node(db, user_subscription_id)
        if not can_switch:
            raise HTTPException(
                status_code=400,
                detail="无法切换节点：订阅未激活或已过期"
            )

        print("✅ 节点切换条件验证通过")

        # 4. 执行节点切换
        updated_sub, message = await switch_user_subscription_node(
            db, user_subscription_id, new_node_id
        )

        if not updated_sub:
            raise HTTPException(status_code=400, detail=message)

        print(f"✅ 节点切换成功: {message}")

        return UserSubscriptionSwitchResponse(
            success=True,
            message=message,
            new_node_id=new_node_id,
            client_ip=updated_sub.client_ip,
            config_updated=True
        )

    except HTTPException:
        raise
    except Exception as e:
        print(f"❌ 节点切换过程出错: {str(e)}")
        import traceback
        print(f"🔍 错误详情: {traceback.format_exc()}")
        raise HTTPException(
            status_code=500,
            detail=f"节点切换过程出错: {str(e)}"
        )


@router.get("/{user_subscription_id}/can-switch")
async def check_can_switch_node(
        user_subscription_id: str,
        db: AsyncSession = Depends(get_db),
        current_user=Depends(get_current_user)
):
    """
    检查用户订阅是否可以切换节点
    """
    try:
        # 验证用户订阅是否存在且属于当前用户
        user_subs = await get_user_subscriptions_by_id(db, user_subscription_id)
        if not user_subs:
            raise HTTPException(status_code=404, detail="用户订阅不存在")

        user_sub = user_subs[0]

        # 检查权限
        if str(user_sub.user_id) != str(current_user.id):
            raise HTTPException(status_code=403, detail="无权操作此订阅")

        can_switch = await can_switch_node(db, user_subscription_id)

        return {
            "can_switch": can_switch,
            "reason": "可以切换节点" if can_switch else "订阅未激活或已过期"
        }

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"检查节点切换状态失败: {str(e)}"
        )